﻿using System;
using System.Collections.Generic;
using Engine;
using Engine.Graphics;
using Game;

namespace Mekiasm
{
    public class IronFurnace : MachineRotateAbleItem, Interface.IDynamicCraft
    {
        public static int Index;

        public int[] FuelCraftSlotIndies => new int[0];

        public int[] CraftSlotIndies => new int[] { 0, 1 };

        public int[] RemainSlotIndies => new int[] { 3 };

        public int[] ResultSlotIndies => new int[] { 4 };

        public int SlotsCount => 6;

        public int BlockValue => blockValue;

        public Point2 CraftSize => new Point2(2, 1);

        public BlockMesh m_standaloneBlockMesh = new BlockMesh();

        public BlockMesh[] m_blockMeshesByData = new BlockMesh[4];

        public IronFurnace() : base( "铁炉")
        {
            
            Model model = ContentManager.Get<Model>("Models/Furnace");
            Matrix boneAbsoluteTransform = BlockMesh.GetBoneAbsoluteTransform(model.FindMesh("Furnace").ParentBone);

            for (int i = 0; i < 4; i++)
            {
                m_blockMeshesByData[i] = new BlockMesh();
                Matrix identity = Matrix.Identity;
                identity *= Matrix.CreateRotationY((float)i * (float)Math.PI / 2f) * Matrix.CreateTranslation(0.5f, 0f, 0.5f);
                m_blockMeshesByData[i].AppendModelMeshPart(model.FindMesh("Furnace").MeshParts[0], boneAbsoluteTransform * identity, makeEmissive: false, flipWindingOrder: false, doubleSided: false, flipNormals: false, Color.White);
            }
            m_standaloneBlockMesh.AppendModelMeshPart(model.FindMesh("Furnace").MeshParts[0], boneAbsoluteTransform * Matrix.CreateTranslation(0f, -0.5f, 0f), makeEmissive: false, flipWindingOrder: false, doubleSided: false, flipNormals: false, Color.White);
            textureSlots = new int[] { 64, 64, 64, 64, 64, 64 };
        }
        public override void DrawBlock(PrimitivesRenderer3D primitivesRenderer, int value, Color color, float size, ref Matrix matrix, DrawBlockEnvironmentData environmentData)
        {
            BlocksManager.DrawMeshBlock(primitivesRenderer, m_standaloneBlockMesh, Color.Gray, size, ref matrix, environmentData);
        }
        public override void GenerateTerrainVertices(Block block, BlockGeometryGenerator generator, TerrainGeometry geometry, int value, int x, int y, int z)
        {
            int num = ILibrary.GetDirection(value);
            if (num < m_blockMeshesByData.Length)
            {
                generator.GenerateShadedMeshVertices(block, x, y, z, m_blockMeshesByData[num], Color.White, null, null, geometry.SubsetAlphaTest);
            }
        }
        public override void OnBlockAdded(SubsystemBlockBehavior blockBehavior, int value, int oldValue, int x, int y, int z)
        {
            ILibrary.AddBlockEntity("铁炉", x, y, z);
        }
        public override void OnBlockRemoved(SubsystemBlockBehavior blockBehavior, int value, int newValue, int x, int y, int z)
        {
            ILibrary.RemoveBlockEntity(x, y, z);
        }
        public override bool OnInteract(SubsystemBlockBehavior blockBehavior, TerrainRaycastResult raycastResult, ComponentMiner componentMiner)
        {
            ComponentIronFurnace furnace = ILibrary.SubsystemBlockEntities.GetBlockEntity(raycastResult.CellFace.X, raycastResult.CellFace.Y, raycastResult.CellFace.Z).Entity.FindComponent<ComponentIronFurnace>();
            componentMiner.ComponentPlayer.ComponentGui.ModalPanelWidget = new IronFurnaceWidget(furnace, componentMiner);
            return base.OnInteract(blockBehavior, raycastResult, componentMiner);
        }

        public void GenerateRecipes(List<MekRecipe> mekRecipe)
        {
            foreach (var c in CraftingRecipesManager.Recipes)
            {
                if (c.RequiredHeatLevel > 0f)
                {
                    var r = new MekRecipe(2, 0, 1, 1).SetDescriction(c.Description);
                    for (int i = 0; i < c.Ingredients.Length; i++)
                    {
                        if (i < 2) r.SetIngredian(i, c.Ingredients[i]);
                        else break;
                    }
                    r.SetRequireHeatLevel(c.RequiredHeatLevel);
                    r.SetRequirePlayerLevel(c.RequiredPlayerLevel);
                    r.SetRemain(0, c.RemainsValue, c.RemainsCount);
                    r.SetResult(0, c.ResultValue, c.ResultCount);
                    r.Message = c.Message;
                    mekRecipe.Add(r);
                }
            }
            mekRecipe.Add(new MekRecipe(1, 0, 1).SetName("橡胶")
                .SetIngredian(0, ILibrary.GetCraftId(Resin.Index))
                .SetResult(0, Rubber.Index).SetRequireHeatLevel(2f)
                .SetRemainNeedCheck());
            mekRecipe.Add(new MekRecipe(1, 0, 1).SetName("锡锭")
                .SetIngredian(0, ILibrary.GetCraftId(OreTin.Index))
                .SetResult(0, TinIngnot.Index).SetRequireHeatLevel(2f)
                .SetRemainNeedCheck());
            mekRecipe.Add(new MekRecipe(1, 0, 1).SetName("橡胶")
                .SetIngredian(0, ILibrary.GetCraftId(RubberWood.Index))
                .SetResult(0, Rubber.Index).SetRequireHeatLevel(2f)
                .SetRemainNeedCheck());
            mekRecipe.Add(new MekRecipe(2, 0, 1).SetName("钢锭")
                .SetIngredian(0, ILibrary.GetCraftId(IronIngotBlock.Index))
                .SetIngredian(1, ILibrary.GetCraftId(CoalDust.Index))
                .SetResult(0, SteelIgnot.Index).SetRequireHeatLevel(3f)
                .SetRemainNeedCheck());
            mekRecipe.Add(new MekRecipe(2, 0, 1).SetName("青铜锭")
                .SetIngredian(0, ILibrary.GetCraftId(CopperIngotBlock.Index))
                .SetIngredian(1, ILibrary.GetCraftId(TinIngnot.Index))
                .SetResult(0, BronzeIngot.Index).SetRequireHeatLevel(3f)
                .SetRemainNeedCheck());

        }

        public void GenerateRecipeWidget(CanvasWidget canvas, ComponentEnergyMachine energyMachine, ComponentMiner miner, ref Action Tick)
        {
            var Component = energyMachine;
            StackPanelWidget hori1 = new StackPanelWidget() { Direction = LayoutDirection.Horizontal ,VerticalAlignment=WidgetAlignment.Center,HorizontalAlignment=WidgetAlignment.Center};
            StackPanelWidget hori2 = new StackPanelWidget() { Direction = LayoutDirection.Horizontal, Margin = new Vector2(0, 5) };
            StackPanelWidget hori3 = new StackPanelWidget() { Direction = LayoutDirection.Horizontal, Margin = new Vector2(0, 5) };
            StackPanelWidget verti1 = new StackPanelWidget() { Direction = LayoutDirection.Vertical };
            StackPanelWidget verti2 = new StackPanelWidget() { Direction = LayoutDirection.Vertical };
            MekProgressWidget craftProgress = new MekProgressWidget(MekProgressWidget.ProgessType.small_right) { Margin = new Vector2(10, 0), Size = new Vector2(60, 20), Name = "craft",VerticalAlignment=WidgetAlignment.Center };
            InventorySlotWidget inventory, inventory1, inventory2, inventory3, inventory4, inventory5;
            inventory = new InventorySlotWidget() { Size = new Vector2(48, 48), BevelColor = Color.Black };
            inventory1 = new InventorySlotWidget() { Size = new Vector2(48, 48), BevelColor = Color.Black };
            inventory2 = new InventorySlotWidget() { Size = new Vector2(48, 48), BevelColor = Color.Red };
            inventory3 = new InventorySlotWidget() { Size = new Vector2(48, 48), BevelColor = Color.Yellow, HorizontalAlignment = WidgetAlignment.Far };
            inventory4 = new InventorySlotWidget() { Size = new Vector2(48, 48), HorizontalAlignment = WidgetAlignment.Far };
            inventory5 = new InventorySlotWidget() { Size = new Vector2(48, 48) };
            inventory.AssignInventorySlot(Component, 0);//物品位1
            inventory1.AssignInventorySlot(Component, 1);//物品位2
            inventory3.AssignInventorySlot(Component, 3);//保留位
            inventory4.AssignInventorySlot(Component, 4);//结果位
            inventory2.AssignInventorySlot(Component, 2);//燃料位
            inventory5.AssignInventorySlot(Component, 5);//风箱位
            hori2.AddChildren(inventory);
            hori2.AddChildren(inventory1);
            hori3.AddChildren(inventory2);
            hori3.AddChildren(inventory5);
            inventory3.AddChildren(new LabelWidget() { Text = "...", HorizontalAlignment = WidgetAlignment.Center, Color = new Color(0, 0, 0, 96) });
            verti2.AddChildren(inventory3);
            verti2.AddChildren(inventory4);
            verti1.AddChildren(hori2);
            verti1.AddChildren(hori3);
            hori1.AddChildren(verti1);
            hori1.AddChildren(craftProgress);
            hori1.AddChildren(verti2);
            canvas.AddChildren(hori1);
            craftProgress.SetProgress(0f);
            Tick += delegate {
                craftProgress.SetProgress(energyMachine.CraftProgress);
            };
        }
    }
}
